package com.jeeplus.test.jlnu.archivalInfo.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.jeeplus.file.repository.AccessoryRepository;
import com.jeeplus.test.jlnu.archivalInfo.domain.vo.ArchivalInfoExcelVO;
import com.jeeplus.test.jlnu.archivalInfo.domain.vo.ArchivalInfoReqVo;
import com.jeeplus.test.jlnu.archivalInfo.mapper.ExportMapper;
import com.jeeplus.test.jlnu.archivalInfo.service.ExportService;
import com.jeeplus.test.jlnu.archivalInfo.utils.ZipUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.File;
import java.io.IOException;


import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@Service
public class ExportServiceImpl implements ExportService {

    @Autowired
    ExportMapper exportMapper;

    @Autowired
    ZipUtils zipUtils;

    @Autowired
    AccessoryRepository accessoryRepository;

    @Override
    public void exportService(ArchivalInfoReqVo archivalInfoExcelVO, List<String> studentId, String officeId) throws IOException {
      List<ArchivalInfoReqVo>  list= exportMapper.getDiffArchivalInfo(archivalInfoExcelVO,officeId);
        String rootDir =System.getProperty("java.io.tmpdir")+"学生目录"; // 根目录
        String zipFilePath = System.getProperty("java.io.tmpdir")+"output.zip"; // 最终压缩包路径

        // 1. 创建根目录
        Files.createDirectories(Paths.get(rootDir));
        Map<String, List<String>> folderToFiles = new HashMap<>();
        // 2. 生成 Excel 并存入不同的文件夹
        for(ArchivalInfoReqVo archivalInfo:list) {
            if (archivalInfo != null){
            String folderPath = rootDir + "/" + archivalInfo.getStudentId() + "-" + archivalInfo.getName();
            Files.createDirectories(Paths.get(folderPath));
            List<String> filePaths = new ArrayList<>();
            List<ArchivalInfoExcelVO> detail = exportMapper.getArchivalInfoDetail(archivalInfo.getId(),officeId);
            String fileName = folderPath + "/" + archivalInfo.getStudentId() + "-" + archivalInfo.getName() + ".xlsx";


            // 检查文件是否存在
            File excelFile = new File(fileName);
            List<ArchivalInfoExcelVO> existingData = new ArrayList<>();
            if (excelFile.exists()) {
                EasyExcel.read(fileName, ArchivalInfoExcelVO.class, new ReadListener<ArchivalInfoExcelVO>() {
                    @Override
                    public void invoke(ArchivalInfoExcelVO data, AnalysisContext context) {
                        existingData.add(data);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                        // 读取完成后的处理
                    }
                }).sheet().doRead();
            }
                existingData.addAll(detail);
                // 如果文件不存在，创建新文件并写入
                EasyExcel.write(fileName, ArchivalInfoExcelVO.class)
                        .includeColumnFiledNames(Arrays.asList("studentId", "name", "materialSort",
                                "materialId", "materialName", "dateTime", "standards", "quantity", "pageCount"))
                        .sheet("学生档案列表")
                        .doWrite(existingData);



            filePaths.add(fileName);

            for (ArchivalInfoExcelVO aiev : detail) {
                if (aiev.getFildUrl() != null && !"".equals(aiev.getFildUrl())) {
                    String[] url = aiev.getFildUrl().split("/");

                    // 提取文件名
                    String fn = url[url.length - 1];

                    // 提取前面的所有地址
                    String address = "/" + url[url.length - 4] + "/" + url[url.length - 3] + "/" + url[url.length - 2];
                    System.out.println("地址：      " + address);
                    System.out.println("文件名：      " + fn);
                    File file = accessoryRepository.get(address, fn);
                    System.out.println(file.getPath());
                    filePaths.add(file.getPath());
                }

            }
                folderToFiles.put(Paths.get(folderPath).toAbsolutePath().toString().replace("\\", "/"), filePaths);
                folderToFiles.put(folderPath, filePaths);
        }
        }


        // 3. 压缩整个根目录
        ZipUtils.zipFolder(rootDir, zipFilePath, folderToFiles);

        // 4. 可选：删除临时文件
        zipUtils.deleteDirectory(new File(rootDir));

        System.out.println("所有 Excel 已生成，并打包至：" + zipFilePath);



    }
    
    @Override
    public void onlyExportService(ArchivalInfoReqVo archivalInfoExcelVO, List<String> studentId, String officeId) throws IOException {
        List<ArchivalInfoReqVo>  list= exportMapper.getDiffArchivalInfo(archivalInfoExcelVO,officeId);
        String rootDir =System.getProperty("java.io.tmpdir")+"学生目录"; // 根目录
        String zipFilePath = System.getProperty("java.io.tmpdir")+"output.zip"; // 最终压缩包路径

        // 1. 创建根目录
        Files.createDirectories(Paths.get(rootDir));
        Map<String, List<String>> folderToFiles = new HashMap<>();
        // 2. 生成 Excel 并存入不同的文件夹
        for(ArchivalInfoReqVo archivalInfo:list) {
            if (archivalInfo != null){
                //String folderPath = rootDir + "/" + archivalInfo.getStudentId() + "-" + archivalInfo.getName();
                List<String> filePaths = new ArrayList<>();
                List<ArchivalInfoExcelVO> detail = exportMapper.getArchivalInfoDetail(archivalInfo.getId(),officeId);
                String fileName = rootDir + "/" + archivalInfo.getStudentId() + "-" + archivalInfo.getName() + ".xlsx";

                // 检查文件是否存在
                File excelFile = new File(fileName);
                List<ArchivalInfoExcelVO> existingData = new ArrayList<>();
                if (excelFile.exists()) {
                    EasyExcel.read(fileName, ArchivalInfoExcelVO.class, new ReadListener<ArchivalInfoExcelVO>() {
                        @Override
                        public void invoke(ArchivalInfoExcelVO data, AnalysisContext context) {
                            existingData.add(data);
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext context) {
                            // 读取完成后的处理
                        }
                    }).sheet().doRead();
                }
                existingData.addAll(detail);
                // 如果文件不存在，创建新文件并写入
                EasyExcel.write(fileName, ArchivalInfoExcelVO.class)
                        .includeColumnFiledNames(Arrays.asList("studentId", "name", "materialSort",
                                "materialId", "materialName", "dateTime", "standards", "quantity", "pageCount"))
                        .sheet("学生档案列表")
                        .doWrite(existingData);

                filePaths.add(fileName);

                folderToFiles.put(Paths.get(rootDir).toAbsolutePath().toString().replace("\\", "/"), filePaths);
                folderToFiles.put(rootDir, filePaths);
            }
        }


        // 3. 压缩整个根目录
        ZipUtils.zipFolder(rootDir, zipFilePath, folderToFiles);

        // 4. 可选：删除临时文件
        zipUtils.deleteDirectory(new File(rootDir));

        System.out.println("所有 Excel 已生成，并打包至：" + zipFilePath);


    }


}
